package com.hgts.config;

import com.hgts.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {
    @ExceptionHandler(BindException.class)
    public R<String> handleRuntimeException(BindException e) {
        log.error(e.toString(), e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        String defaultMessage = objectError.getDefaultMessage();
        System.out.println(defaultMessage);
        return R.error(defaultMessage);
    }
}
